package org.mqtt;

import lombok.Data;

@Data
public class CipherConfig {

    public static final String AES_CODER_USERNAME = "^[a-zA-Z0-9\\-]+\\|[aer]=\\d+,[aer]=\\d+,[aer]=\\d+$";

    private static final String authMethod_key = "a";

    private static final String random_key = "r";

    private static final String encryptMethod_key = "e";

    private String authMethod = "1";

    private String random ;

    private String serverRandom ;

    private String encryptMethod = "1";

    private String deviceId;

    public CipherConfig(String mqttClientId) {
        if (mqttClientId.matches(AES_CODER_USERNAME)) {
            String[] params = mqttClientId.split("\\|");
            this.deviceId = params[0];
            String[] methods = params[1].split(",");
            for (String method : methods) {
                if (method.startsWith(authMethod_key)) {
                    this.authMethod = method.split("=")[1];
                }
                if (method.startsWith(random_key)) {
                    this.random = method.split("=")[1];
                }
                if (method.startsWith(encryptMethod_key)) {
                    this.encryptMethod = method.split("=")[1];
                }

            }
        }
    }

    public String getServerRandom() {
        return serverRandom;
    }

    public void setServerRandom(String serverRandom) {
        this.serverRandom = serverRandom;
    }

    public CipherConfig(String deviceId,String random) {
        this.deviceId = deviceId;
        this.random = random;
    }

    public CipherConfig(String deviceId,String encryptMethod,String random) {
        this.deviceId = deviceId;
        this.random = random;
        this.encryptMethod = encryptMethod;
    }

    public String getClientId() {
//        return String.format("%s|a=%s,e=%s,r=%s",deviceId,authMethod,encryptMethod,random);
        return String.format("%s|a=%s,e=%s,r=%s",deviceId,authMethod,encryptMethod,random);
    }

    public String getNonce() {
        return String.format("%s%s", deviceId, random);
    }
}
